<?php

namespace utils;
use mysqli;
use RuntimeException;

class MysqlDBUtils
{
    private $host = "localhost";
    private $user = "root";
    private $pass = "123456";
    private $db = "bookprogram";
    private $mysql;

    public function prepareQuery($sql)
    {
        $conn = new mysqli($this->host, $this->user, $this->pass, $this->db);
        $result = mysqli_query($conn, $sql);
        if (!$result) {
            echo("预处理失败：" . $conn->error . "sql:$sql");
            $conn->close();
            return false;
        }
        //查询语句
        if (strpos(strtoupper($sql), 'SELECT') === 0) {
            $data = $this->fetchAll($result);
            $conn->close();
            return $data;
        } else {
            //增删改语句
            $affectedRows = mysqli_affected_rows($conn);
            $conn->close();
            return $affectedRows;
        }
    }

//    从结果集种获取所有的数据（关联数组）
    private function fetchAll($result): array
    {
        $data = [];
        while ($row = mysqli_fetch_assoc($result)) {
            $data[] = $row;
        }
        mysqli_free_result($result);
        return $data;
    }
//  转义方法
    public function escapeString($value) {
        $conn = new mysqli($this->host, $this->user, $this->pass, $this->db);
        return $conn->real_escape_string($value); // 使用mysqli内置转义
    }

    public function prepareExecute(string $sql, array $params)
    {
        // 建立持久化连接
        static $conn = null;
        if (!$conn) {
            $conn = new mysqli($this->host, $this->user, $this->pass, $this->db);
            if ($conn->connect_error) {
                throw new RuntimeException("数据库连接失败: " . $conn->connect_error);
            }
        }

        // 准备语句
        $stmt = $conn->prepare($sql);
        if (!$stmt) {
            throw new RuntimeException("预处理失败: " . $conn->error);
        }

        // 绑定参数
        if (!empty($params)) {
            $types = '';
            $bindParams = [];

            foreach ($params as &$param) {
                if (is_int($param)) {
                    $types .= 'i';
                } elseif (is_double($param)) {
                    $types .= 'd';
                } else {
                    $types .= 's';
                }
                $bindParams[] = &$param;
            }

            array_unshift($bindParams, $types);
            call_user_func_array([$stmt, 'bind_param'], $bindParams);
        }

        // 执行查询
        if (!$stmt->execute()) {
            throw new RuntimeException("执行失败: " . $stmt->error);
        }

        // 处理结果
        $result = $stmt->get_result();
        if ($result instanceof \mysqli_result) {
            $data = [];
            while ($row = $result->fetch_assoc()) {
                $data[] = $row;
            }
            $result->free();
            $stmt->close();
            return $data;
        } else {
            $affectedRows = $conn->affected_rows;
            $stmt->close();
            return $affectedRows;
        }
    }



}